package com.youdianstar.app.support.paging

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.youdianstar.app.api.ApiService
import com.youdianstar.app.common.PAGE_SIZE
import com.youdianstar.app.entity.CouponInfo
import com.youdianstar.app.common.event.NetEventLiveData

import java.io.IOException


/**
 * File: CouponPagingSource
 * Author: 82149 Create: 2022/2/25 18:01
 * Changes (from 2022/2/25)
 * --------------------------------------------------
 * description:
 * ---------------------------------------------------
 *
 */
class RedeemPagingSource(
    private val service: ApiService,
    private val type: Int,
    private val eventLiveData: NetEventLiveData? = null
) : PagingSource<Int, CouponInfo>() {

    override fun getRefreshKey(state: PagingState<Int, CouponInfo>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, CouponInfo> {
        val index = params.key ?: 0 //当前数据下标,从0开始
        try {
            //type: 0-通用优惠券 1-商家优惠券
            val data = service.getCouponsInfo(type,index)
            val dataSize: Int = if (null == data.data) 0 else data.data!!.size
            //val preKey = if (index > 0) index - PAGE_SIZE else null
            if (index==0 && dataSize==0){
                eventLiveData?.postValue(NetEventLiveData.Result.RESULT_EMPTY)
            } else{
                data.data?.forEach { ins->
                    ins.dataType = type
                }
                eventLiveData?.postValue(NetEventLiveData.Result.RESULT_OK)
            }
            return LoadResult.Page(
                data.data!!, prevKey = null,
                nextKey = (if (dataSize < PAGE_SIZE) null else dataSize + index)
            )
        } catch (e: IOException) {
            if (index==0)
                eventLiveData?.postValue(NetEventLiveData.Result.RESULT_ERROR)
            //LogUtil.e("---IOE:"+e.printStackTrace())
            return LoadResult.Error(e)
        } catch (e: Exception) {
            //LogUtil.e("---EX:"+e.printStackTrace())
            eventLiveData?.postValue(NetEventLiveData.Result.NET_ERROR)
            return LoadResult.Error(e)
        }
    }

}